package com.atguigu.gmall.auth;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class SimpleThreadPoolExecutor {

    public static void main(String[] args) {
        SimpleThreadPoolExecutor executor = new SimpleThreadPoolExecutor(5, 10);
        for (int i = 0; i < 500; i++) {
            Integer taskId = i;
            executor.execute(() -> {
                System.out.println("Task " + taskId + " is running by " + Thread.currentThread().getName());
            });
        }
    }

    private final BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
    private final List<Thread> threads = new ArrayList<>();
    private final int corePoolSize;
    private final int maximumPoolSize;
    private volatile boolean isShutdown = false;

    public SimpleThreadPoolExecutor(int corePoolSize, int maximumPoolSize) {
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;

        // 初始化核心线程  
        for (int i = 0; i < corePoolSize; i++) {
            addThread();
        }
    }

    private void addThread() {
        if (threads.size() >= maximumPoolSize || isShutdown) {
            return;
        }

        Thread thread = new Thread(() -> {
            while (!isShutdown || !workQueue.isEmpty()) {
                try {
                    Runnable task = workQueue.take();
                    task.run();
                } catch (InterruptedException e) {
                    // 处理中断异常，可能需要重新中断线程或退出循环  
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        });
        thread.start();
        threads.add(thread);
    }

    public void execute(Runnable task) {
        if (isShutdown) {
            throw new IllegalStateException("ThreadPoolExecutor is shutdown");
        }

        if (threads.size() < maximumPoolSize) {
            // 如果线程数小于最大线程数，尝试直接执行任务  
            if (threads.size() < corePoolSize) {
                addThread(); // 尝试添加一个新线程  
            } else {
                addThread();
            }
//            if (!workQueue.offer(task)) {
//                // 如果队列已满且线程数小于最大线程数，则添加新线程
//                addThread();
//            }
        } else {
            // 队列已满且线程数已达到最大，将任务加入队列（可能阻塞）  
            try {
                workQueue.put(task);
            } catch (InterruptedException e) {
                // 处理中断异常  
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
        }
    }

    public void shutdown() {
        isShutdown = true;
        // 可以考虑中断所有线程或等待它们完成  
    }

    // 其他方法，如获取线程池状态、任务拒绝策略等可以根据需要添加  
}